import { map_setting } from '@/apps/maps/models/map_setting'

/**
 * 遍历map_setting表，查找type为生物的项，读取其detail中的race、level、affixes
 * @returns Promise<Array<{race: string, level: [number, number], affixes: string[]}>>
 */
async function generateMap() {
  const allSettings = await map_setting.findAllValues()
  const creatures: Array<{ race: string; level: number; affixes: string[] }> =
    []

  for (const setting of allSettings) {
    if (setting.type === '生物') {
      let detail = setting.detail
      if (typeof detail === 'string') {
        try {
          detail = JSON.parse(detail)
        } catch {
          continue
        }
      }
      const race = detail.race || ''
      // detail.level是字符串，例如"1-5"，转变为数字，level取这个范围内随机整数
      let level = 1
      if (typeof detail.level === 'string' && detail.level.includes('-')) {
        const [min, max] = detail.level.split('-').map(Number)
        if (!isNaN(min) && !isNaN(max)) {
          level = Math.floor(Math.random() * (max - min + 1)) + min
        }
      } else if (typeof detail.level === 'number') {
        level = detail.level
      }
      // detail.affixes 是个数组，随机抽取词条，初始概率100%，每抽一次成功率降低十倍，抽取失败后停止
      const affixes: string[] = []
      if (Array.isArray(detail.affixes)) {
        let successRate = 1.0
        for (const affix of detail.affixes) {
          if (Math.random() < successRate) {
            affixes.push(affix)
            successRate /= 10 // 每次成功后降低十倍成功率
          } else {
            break // 抽取失败，停止
          }
        }
      }
      creatures.push({ race, level, affixes })
    }
  }
  return creatures
}
